<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
      <span>{{formData.title}}</span>
    </div>
    <div class="text item el-over-auto first-codeAdd">
      <el-form :model='formData' :inline="true" ref='formData' label-width="85px" class='codeRuleForm'>
        <el-row class='code-first-row'>
          <span class='basic-info'>
            <div class='line-style'></div>基本信息
          </span>
          <el-form-item label="启用状态:" class='status-item'>
            <el-radio-group v-model="formData.enabled">
              <el-radio :label="item.value" :key="item.value" v-for="item in isChecked">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row class='code-second-row'>
          <el-col :span='6'>
            <el-form-item label="编码规则:" prop="ruleCode" :rules="[{ required: true, message: '请输入基本信息'}]">
              <el-input v-model="formData.ruleCode" v-if="formData.title =='编辑编码规则'" readonly></el-input>
              <el-input v-model="formData.ruleCode" v-if="formData.title =='新增编码规则'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='6'>
            <el-form-item label="规则名称:" prop="ruleName" :rules="[{ required: true, message: '请输入规则名称'}]">
              <el-input v-model="formData.ruleName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='6'>
            <el-form-item label="分隔符:" prop="decollator">
              <el-input v-model.trim="formData.decollator"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider class='divider-code'></el-divider>
      <el-row>
        <span class='combination-title'>
          <div class='line-style'></div>规则组合段
        </span>
        <el-button class='combination-add-button' type="primary" plain @click='combinationAdd("compareFormData")'>新增<i
            class="el-icon-plus"></i></el-button>
      </el-row>
      <el-row class='combination-table'>
        <el-table :data="tableData" border ref='tableData' stripe>
          <el-table-column prop="segmentOrder" type="index" align="center" label="序号" min-width="70px"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="segmentName" label="段类型" min-width="200px" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="segmentVal" label="值" min-width="200px" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="segmentLen" align="center" label="长度" min-width="90px" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="triggerFlag" align="center" label="是否重新编号" min-width="120px" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="排序" width="110px" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" title="上移" type="text" @click="handleUp(scope.$index, scope.row)"><i class="el-icon-top"></i></el-button>
              <el-button class="td-btn-icon" title="下移" type="text" @click="handleDown(scope.$index, scope.row)"><i
                  class="el-icon-bottom"></i></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="110px" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" title="编辑" @click='combinationEdit(scope.$index, scope.row)'
                icon="el-icon-edit"></el-button>
              <el-button class="td-btn-icon" type="text" title="删除" @click.native.prevent="combitionDelete(scope.$index, scope.row)"
                icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 规则组合段新增/编辑弹框 -->
      <el-dialog :title="combinationTitle" :visible.sync="dialogVisible" width="40%" @close="handleClose"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form label-width="90px" :model="compareFormData" ref='compareFormData'>
          <el-form-item label="段类型:" prop="segmentCat" :rules="[{ required: true, message: '请选择段类型',trigger: 'blur'}]">
            <el-select v-model="compareFormData.segmentCat" placeholder="请选择" @change="selectGet">
              <el-option v-for="item in combinationSelectData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="值:" prop="segmentVal" v-if="compareFormData.segmentCat == '68d07f137ebc482f926df0aafa626062'"
            :rules="[{ required: true,trigger: 'blur', message: '请输入值'}]">
            <el-col :span="8">
              <el-input v-model="compareFormData.segmentVal" placeholder="请输入"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="长度:" prop="segmentLen" v-if="compareFormData.segmentCat == 'bc632a23a6264e3dae9776157e077956'||compareFormData.segmentCat == 'cf35bbddcb2440d88e0efc350968ceb3'"
            :rules="[{ required: true,trigger: 'blur', message: '请输入长度'},{ type: 'number', message: '请输入数字',trigger: 'blur'}]">
            <el-col :span="9">
              <el-input v-model.number="compareFormData.segmentLen" placeholder="请输入"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="日期格式:" prop="segmentVal" v-if="compareFormData.segmentCat == '06933656bd8946868780d3d3342d76ca'"
            :rules="[{ required: true, message: '请选择日期'}]">
            <el-select v-model="compareFormData.segmentVal" placeholder="请选择">
              <el-option v-for="item in dateSelectData" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="初始值:" prop="segmentVal" v-if="compareFormData.segmentCat == 'cf35bbddcb2440d88e0efc350968ceb3'"
            :rules="[{ required: true,trigger: 'blur', message: '请输入初始值'}, { type: 'number', message: '请输入数字',trigger: 'blur'}]">
            <el-col :span="9">
              <el-input v-model.number="compareFormData.segmentVal" placeholder="请输入"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item v-if="compareFormData.segmentCat == '3761a597d15f4e91a4e12eacea4a39ca'|| compareFormData.segmentCat == '06933656bd8946868780d3d3342d76ca'|| compareFormData.segmentCat == 'bc632a23a6264e3dae9776157e077956'">
            <el-col :span="8">
              <el-checkbox v-model="compareFormData.triggerFlag" true-label="是" false-label="否" border>值变化时是否重新编号</el-checkbox>
            </el-col>
          </el-form-item>
          <el-form-item v-if="compareFormData.segmentCat == '3761a597d15f4e91a4e12eacea4a39ca'">
            <el-card class="box-card el-card-flex el-flex" style='box-shadow: none;'>
              <div slot="header" class="clearfix">
                <span>对照表</span>
                <el-button type="primary" plain style="float: right;" @click='constrastAdd'>新增<i class="el-icon-plus"></i></el-button>
              </div>
              <div class="text item el-flex el-box-column">
                <el-table @cell-mouse-enter="handleMouseEnter" @cell-mouse-leave="handleMouseOut" :data="compareTable"
                  border ref='tableData' stripe style="overflow: auto">
                  <el-table-column type="index" align="center" label="序号" min-width="55px" sortable
                    :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column prop="originalVal" label="参考值" min-width="150px" sortable :show-overflow-tooltip="true">
                    <template slot-scope="{row,$index}">
                      <el-input v-model="row.originalVal" ref='currentInputData'></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="actualVal" label="实际值" min-width="150px" sortable :show-overflow-tooltip="true">
                    <template slot-scope="{row,$index}">
                      <el-input v-model="row.actualVal"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="120px" sortable align="center">
                    <template slot-scope="scope">
                      <el-button class="td-btn-icon" type="text" title="删除" @click.native.prevent="compareDelete(scope.$index, scope.row)"
                        icon="el-icon-delete"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click='compareSave("compareFormData")'>确定 <i class="el-icon-document-checked"></i></el-button>
          <el-button @click='compareSaveCancel("compareFormData")'>取消 <i class="el-icon-refresh-left"></i></el-button>
        </span>
      </el-dialog>
    </div>
    <div style="text-align: right;margin-right: 8px;margin-bottom: 8px;margin-top: 8px;">
      <el-button type="primary" @click="codeRuleSave('formData')">保存 <i class="el-icon-document-checked"></i>
      </el-button>
      <el-button type="danger" @click="cancelEvt('formData')">关闭 <i class="el-icon-close"></i>
      </el-button>
    </div>
  </el-card>
</template>
<script>
  import {
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    Divider
  } from 'element-ui'
  import {
    comboBoxSelect,
    reviseRules,
    addRules,
    compareTableDel,
    compareTableDels
  } from '@/api/system/codeRule/addCodeRule.js'
  export default {
    name: "addCodeRule",
    components: {
      'el-dialog': Dialog, // 对话框
      'el-table': Table, // 表格
      'el-table-column': TableColumn, // 表格列
      'el-pagination': Pagination, // 分页
      'el-divider': Divider
    },
    data() {
      return {
        checkSegmentId: true, //判断segemenId是否存在
        formData: {},
        id: '', //下拉初始化显示值
        segmentLen: "", //长度校验
        name: '',
        combinationTitle: '',
        ids: [],
        title: '',
        restRow: '', //对照表修改
        currentRowIndex: "",
        dialogVisible: false,
        dialogContrast: false,
        row: {},
        combinationSelectData: [], //组合段下拉数据源
        dateSelectData: [], //日期下拉数据源
        radio: '',
        tableData: [], //规则组合段表格数据
        compareTable: [], //对照表数据
        compareFormData: {}, //规则组合段新增/编辑表格数据
        compareForm: {}, //规则组合保存结果
        switchs: [], //对照表组合保存结果
        segmentNamelabel: '', //组合段下拉数据源显示值
        changeCompareTable: [],
        isChecked: [{
            label: "开启",
            value: 'Y'
          },
          {
            label: "关闭",
            value: 'N'
          }
        ],
      }
    },
    created() {
      this.formData = this.$route.params.row
      if (this.$route.params.row.segments) {
        this.tableData = this.$route.params.row.segments
        this.tableData.forEach(item => {
          if (item.triggerFlag == "N") {
            item.triggerFlag = "否"
          } else if (item.triggerFlag == "Y") {
            item.triggerFlag = "是"
          } else {
            item.triggerFlag = ""
          }
        })
        window.onresize = () => {
          this.$refs.tableData.doLayout() //监听窗口变化，重绘表格布局
        }
      } else {
        this.tableData = []
      }
    },
    methods: {
      selectGet(vId) { //组合段下拉数据源显示值匹配
        this.$refs.compareFormData.clearValidate()
        this.compareFormData.segmentVal = ''
        this.compareFormData.segmentLen = ''
        let obj = {}
        obj = this.combinationSelectData.find((item) => {
          return item.id === vId
        });
        this.segmentNamelabel = obj.name
        if (this.segmentNamelabel == '固定值' || this.segmentNamelabel == '流水号') {
          this.compareFormData.triggerFlag = ''
        } else {
          this.compareFormData.triggerFlag = '否'
        }

        if (this.combinationTitle == "新增类型") {
          this.compareTable = []
        } else {
          if (this.segmentNamelabel != "对照表") {
            this.compareTable = []
          } else {
            if (this.compareTable == null) {
              this.compareTable = []
            } else {
              this.compareTable = this.changeCompareTable
            }
          }
        }
      },
      combinationSelect() { //组合段下拉数据源
        comboBoxSelect('16d9acd73ea54af6a581479634cf5b4f').then(res => {
          if (res.data.code == 10000) {
            this.combinationSelectData = res.data.data
          }
        })
      },
      dateSelect() { //日期下拉数据源
        // this.axios.get('/eosDict/comboBoxData/4d9c6e5a6f28499397cf3dd681425a61')
        comboBoxSelect('4d9c6e5a6f28499397cf3dd681425a61').then(res => {
          if (res.data.code == 10000) {
            this.dateSelectData = res.data.data
          }
        })
      },
      editCodeRuleSave() { //编辑页保存
        var status
        var tableStatus
        if (this.tableData.length == 0) {
          Message({
            type: 'warning',
            message: '表格数据不能为空'
          })
        } else {
          this.tableData.forEach(item => {
            if (item.segmentName == "流水号") {
              status = true
              return false
            }
          })
          if (status == true) {
            this.tableData.forEach((item, index) => {
              item.segmentOrder = index
              if (item.triggerFlag == "否") {
                item.triggerFlag = "N"
              } else if (item.triggerFlag == "是") {
                item.triggerFlag = "Y"
              } else {
                item.triggerFlag = ""
              }
            })
            // this.axios.put('rule/update', {
            //   "enabled": this.formData.enabled,
            //   "ruleCode": this.formData.ruleCode,
            //   "ruleName": this.formData.ruleName,
            //   "decollator": this.formData.decollator,
            //   "ruleId": this.$route.params.row.ruleId,
            //   "segments": this.tableData
            // })
            reviseRules({
              "enabled": this.formData.enabled,
              "ruleCode": this.formData.ruleCode,
              "ruleName": this.formData.ruleName,
              "decollator": this.formData.decollator,
              "ruleId": this.$route.params.row.ruleId,
              "segments": this.tableData
            }).then(res => {
              if (res.data.code == 10000) {
                Message({
                  type: 'success',
                  message: '保存成功'
                });
                this.$router.go(-1)
              }
            })
          } else {
            Message({
              type: 'warning',
              message: '流水号为必填值'
            });
          }
        }

      },
      addCodeRuleSave() { //新增页保存
        var flag
        this.tableData.forEach(item => {
          if (item.segmentName == "流水号") {
            flag = true
            return false
          }
        })
        if (flag == true) {
          this.tableData.forEach((item, index) => {
            item.segmentOrder = index
            if (item.triggerFlag == "否") {
              item.triggerFlag = "N"
            } else if (item.triggerFlag == "是") {
              item.triggerFlag = "Y"
            } else {
              item.triggerFlag = ""
            }
          })
          // this.axios.post('/rule/save', {
          //   "enabled": this.formData.enabled,
          //   "ruleCode": this.formData.ruleCode,
          //   "ruleName": this.formData.ruleName,
          //   "decollator": this.formData.decollator,
          //   "segments": this.tableData
          // })
          addRules({
            "enabled": this.formData.enabled,
            "ruleCode": this.formData.ruleCode,
            "ruleName": this.formData.ruleName,
            "decollator": this.formData.decollator,
            "segments": this.tableData
          }).then(res => {
            if (res.data.code == 10000) {
              Message({
                type: 'success',
                message: '保存成功'
              });
              this.$router.go(-1)
            }
          })
        } else {
          Message({
            type: 'warning',
            message: '流水号为必填值'
          });
        }
      },
      codeRuleSave(formData) { //编码规则保存
        this.$refs[formData].validate((valid) => {
          if (valid) {
            if (this.formData.title == '编辑编码规则') {
              this.editCodeRuleSave()
            } else {
              this.addCodeRuleSave()
            }
          } else {
            Message({
              type: 'warning',
              message: '请完成必填值'
            });
          }
        });
      },
      handleMouseEnter: function(row, column, cell, event) {},
      handleMouseOut: function(row, column, cell, event) {},
      handleClose() { //X关闭
        this.$refs.compareFormData.clearValidate()
      },
      constrastAdd() { //对照表新增
        this.compareTable.push({
          originalVal: '',
          actualVal: ''
        })
      },
      combinationAdd(compareFormData) { //规则组合段新增
        this.dialogVisible = true
        this.combinationTitle = "新增类型"
        this.compareFormData = {
          segmentVal: '',
          segmentLen: '',
          triggerFlag: '否'
        }
        this.compareTable = []
        this.combinationSelect()
        this.dateSelect()
      },
      combinationEdit(index, row) { //规则组合段编辑
        this.dialogVisible = true
        this.combinationTitle = "编辑类型"
        this.combinationSelect()
        this.dateSelect()
        var cloneData = JSON.parse(JSON.stringify(row))
        this.compareFormData = JSON.parse(JSON.stringify(row))
        this.compareTable = cloneData.switchs
        this.changeCompareTable = cloneData.switchs
        if (row.switchs != null) {
          this.compareTable.forEach(item => {
            this.ids.push(item.switchId)
          })
        } else {
          this.ids = []
        }
        this.currentRowIndex = index
      },
      addCompareSave() { //对照表新增确认
        this.compareFormData.segmentName = this.segmentNamelabel
        if (this.segmentNamelabel == "对照表") {
          if (this.compareTable.length == 0) {
            Message({
              type: 'warning',
              message: '对照表数据不能为空'
            })
          } else {
            var addInputData
            this.compareTable.forEach(item => {
              if (item.originalVal == '' || item.actualVal == '') {
                addInputData = false
                return false
              }
            })
            if (addInputData == false) {
              Message({
                type: 'warning',
                message: '填写数据不能为空'
              })
            } else {
              this.compareFormData.switchs = this.compareTable
              this.tableData.push(this.compareFormData)
              this.compareFormData.segmentOrder = this.tableData.length + 1
              this.dialogVisible = false
            }
          }
        } else {
          this.tableData.push(this.compareFormData)
          this.compareFormData.segmentOrder = this.tableData.length + 1
          this.dialogVisible = false
        }
      },
      editCompareSave() { //对照表编辑确认
        let obj = {}
        obj = this.combinationSelectData.find((item) => {
          return item.id == this.compareFormData.segmentCat
        });
        this.segmentNamelabel = obj.name
        this.compareFormData.segmentName = this.segmentNamelabel
        if (this.segmentNamelabel == "对照表") {
          var inputData
          this.compareTable.forEach(item => {
            if (item.originalVal == '' || item.actualVal == '') {
              inputData = false
              return false
            }
          })
          if (inputData == false) {
            Message({
              type: 'warning',
              message: '填写数据不能为空'
            })
          } else {
            this.compareFormData.switchs = this.compareTable
            this.tableData.splice(this.currentRowIndex, 1, this.compareFormData)
            this.dialogVisible = false
          }
        } else {
          if (this.ids[0] != undefined) {
            // this.axios.post('/ruleSegSwitch/del',
            //   this.ids
            // )
            compareTableDel(this.ids)
          }
          this.tableData.splice(this.currentRowIndex, 1, this.compareFormData)
          this.dialogVisible = false
        }
      },
      compareSave(compareFormData) { //对照表确认
        this.$refs[compareFormData].validate((valid) => {
          if (valid) {
            if (this.combinationTitle == '新增类型') {
              this.addCompareSave()
            } else {
              this.editCompareSave()
            }
          } else {
            Message({
              type: 'warning',
              message: '请完成必填值'
            })
          }
        })
      },
      compareSaveCancel(compareFormData) { //对照表取消
        this.$refs.compareFormData.clearValidate()
        this.dialogVisible = false
      },
      handleUp(index, row) { //上移
        if (index == 0) {
          Message({
            type: 'warning',
            message: '这已经是第一条了'
          })
        } else {
          let temp = this.tableData[index - 1];
          this.$set(this.tableData, index - 1, this.tableData[index])
          this.$set(this.tableData, index, temp)
        }
      },
      handleDown(index, row) { //下移
        if (index == this.tableData.length - 1) {
          Message({
            type: 'warning',
            message: '这已经是最后一条了'
          })
        } else {
          let i = this.tableData[index + 1];
          this.$set(this.tableData, index + 1, this.tableData[index])
          this.$set(this.tableData, index, i)
        }
      },
      cancelEvt(formData) { //关闭
        this.$refs[formData].clearValidate();
        this.$router.go(-1)
      },
      combitionDelete(index, row) { //规则组合段表格删除
        MessageBox.confirm('您是否确定删除选中内容', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            if (row.segmentId) {
              // this.axios.delete('/ruleSegments/' + row.segmentId)
              compareTableDels(row.segmentId).then(res => {
                if (res.data.code == 10000) {
                  this.tableData.splice(index, 1)
                  Message({
                    type: 'success',
                    message: "删除成功"
                  });
                } else {
                  Message({
                    type: 'warning',
                    message: "删除失败"
                  });
                }
              })
            } else {
              this.tableData.splice(index, 1)
              Message({
                type: 'success',
                message: "删除成功"
              });
            }
          }).catch(() => {});
      },
      compareDelete(index, row) { //对照表删除
        MessageBox.confirm('您是否确定删除选中内容', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            if (row.switchId) {
              // this.axios.post('/ruleSegSwitch/del',
              //   [row.switchId]
              // )
              compareTableDel([row.switchId]).then(res => {
                if (res.data.code == 10000) {
                  this.compareTable.splice(index, 1);
                  this.tableData[this.currentRowIndex].switchs.splice(index, 1);
                  Message({
                    type: 'success',
                    message: "删除成功"
                  });
                } else {
                  Message({
                    type: 'warning',
                    message: "删除失败"
                  });
                }
              }).catch(() => {});
            } else {
              this.compareTable.splice(index, 1);
              Message({
                type: 'success',
                message: "删除成功"
              });
            }
          }).catch(() => {});
      }
    },
  }
</script>
<style lang="scss">
  .basic-info {
    font-size: 14px;
    line-height:32px;
  }
.code-first-row{
  margin-bottom: 6px;
}
.code-second-row{
  margin-bottom: 3px;
}
  .first-codeAdd {
    padding-top: 21px !important;
  }

  .line-style {
    width: 2px;
    height: 8px;
    background: #409EFF;
    display: inline-block;
    margin-right: 6px;
    vertical-align: middle;
  }

  .codeRuleForm {
    .el-form-item__label {
      text-align: left;
      padding: 0px 15px 0 0;
    }
  }

  .combination-title {
    line-height: 32px;
    font-size: 14px;
  }

  .combination-add-button {
    float: right;
    margin-right: 20px;
  }

  .combination-table {
    margin-top: 14px;
  }

  .status-item {
    float: right;
    padding-right: 10px;
  }
</style>
